<template>
  <section class="waitingNotice-list">
    <a-page-header
        style="background-color: #fff"
        title="收款通知"
        :backIcon="false"
    />
    <!-- 统计模块 -->
    <section class="statics">
      <a-row
          type="flex"
          justify="space-around"
          align="middle"
          style="height: 100px"
      >
        <a-col span="8">
          <a-statistic title="已生成" :value="totalCount"/>
        </a-col>
        <a-col
            span="8"
            style="
            border-left: 1px solid #f5f5f5;
            border-right: 1px solid #f5f5f5;
          "
        >
          <a-statistic title="短信发送成功" :value="smsCount"/>
        </a-col>
        <a-col span="8">
          <a-statistic title="邮箱发送成功" :value="emailCount"/>
        </a-col>
      </a-row>
    </section>

    <!-- 表格 -->
    <a-table
        sticky
        :dataSource="dataList"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        :rowSelection="rowSelection"
        rowKey="id"
        :scroll="{ x: 'max-content' }"
        class="mt-10"
    >
      <template
          #customFilterDropdown="{
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          column,
        }"
      >
        <div style="padding: 8px">
          <a-input
              ref="searchInput"
              placeholder="请输入租客名称"
              :value="selectedKeys[0]"
              style="width: 188px; margin-bottom: 8px; display: block"
              @change="
              (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
            "
              @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
          />
          <a-button
              type="primary"
              size="small"
              style="width: 90px; margin-right: 8px"
              @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
          >
            <template #icon>
              <SearchOutlined/>
            </template>
            搜索
          </a-button>
          <a-button
              size="small"
              style="width: 90px"
              @click="handleReset(clearFilters, confirm)"
          >
            重置
          </a-button>
        </div>
      </template>

      <template #customFilterIcon="{ filtered, column }">
        <template v-if="column.key == 'owner_name'">
          <search-outlined
              :style="{ color: filtered ? '#108ee9' : undefined }"
          />
        </template>
        <template v-else>
          <filter-filled/>
        </template>
      </template>

      <template #title>
        <a-row
            type="flex"
            justify="space-between"
            class="table-header"
            align="middle"
            style="
            border-bottom: 1px solid #f0f0f0;
            padding-bottom: 20px;
            padding-left: 10px;
            padding-right: 10px;
          "
        >
          <a-col :span="12">
            <a-range-picker
                v-model:value="dateRange"
                class="range-picker"
                @change="onRangeChange"
                :placeholder="['创建起始时间', '创建结束时间']"
                :ranges="{
                本周: [
                  moment().startOf('week').subtract('weeks'),
                  moment().endOf('week').subtract('weeks'),
                ],
                本月: [
                  moment().startOf('months').subtract('months'),
                  moment().endOf('months').subtract('months'),
                ],
              }"
            />
          </a-col>
          <a-col :span="6" style="display: flex; justify-content: flex-end">
            <a-button
                class="btn-class"
                @click="printReceipt"
                :disabled="!selectedRows.length"
            >打印
            </a-button>
          </a-col>
        </a-row>
      </template>

      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'sms_status'">
          <!-- 1:失败；2;成功 -->
          <a-tag v-if="text == 1" color="#ff3141">{{
              record.sms_status_txt
            }}
          </a-tag>
          <a-tag v-else-if="text == 2" color="#00b578">{{
              record.sms_status_txt
            }}
          </a-tag>
          <span v-else>{{ record.sms_status_txt }}</span>
        </template>
        <template v-if="column.key === 'email_status'">
          <a-tag v-if="text == 1" color="#ff3141">{{
              record.email_status_txt
            }}
          </a-tag>
          <a-tag v-else-if="text == 2" color="#00b578">{{
              record.email_status_txt
            }}
          </a-tag>
          <span v-else>{{ record.email_status_txt }}</span>
        </template>
        <template v-if="column.key === 'wechat_status'">
          <a-tag v-if="text == 1" color="#ff3141">失败</a-tag>
          <a-tag v-else-if="text == 2" color="#00b578">成功</a-tag>
          <span v-else>--</span>
        </template>
        <template v-if="column.key === 'action'">
          <span>
            <a href="" @click.prevent="sendAgain(record)">重新发送</a>
          </span>
          <span v-if="record.file_path" style="margin-left: 20px">
            <a href="" @click.prevent="previewFile(record)">下载</a>
          </span>
        </template>
      </template>
    </a-table>

    <resend-notice
        @closeDrawer="resendNoticeClose"
        @success="resendNoticeSuccess"
        :visible="resendNoticeVisible"
        :data="resendNoticeData"
        :noticeId="resendNoticeId"
        :taskKey="resendNoticeTaskKey"
    ></resend-notice>

    <!-- 预览+下载 -->
    <ElectronContractModal
        :visible="electronContractVisible"
        :urlData="previewUrlData"
        :esignDetail="{
        esignCheck: true,
      }"
        title="在线预览"
        @close="electronContractVisible = false"
    />

    <!--打印-->
    <print-modal :file_list="printList" :usePrint="showModal" @change="showModal=false"/>

  </section>
</template>

<script>
import {defineComponent, ref, computed, watch, reactive, toRefs} from "vue";
import request from "../../../common/utils/request";
import {useRouter} from "vue-router";
import {SearchOutlined, FilterFilled, CloudDownloadOutlined} from "@ant-design/icons-vue";
import moment from "moment";
import ResendNotice from "./ResendNotice.vue";
import {message} from 'ant-design-vue'
import {previewFile} from '@wecom/jssdk'
import ElectronContractModal from '@/components/ElectronContractModal/index.vue'
import PrintModal from '@/components/Bill/PrintModal.vue'

export default defineComponent({
  name: "waitingNoticeList",
  methods: {previewFile},
  components: {
    PrintModal,
    CloudDownloadOutlined,
    ElectronContractModal, SearchOutlined, ResendNotice, FilterFilled
  },
  setup() {
    const $router = useRouter();

    const dateRange = ref([]);

    const buildList = ref([]);
    const selectedBuildList = ref([]);
    const smsList = ref([]);
    const emailList = ref([]);
    const weChatFilterList = ref([]);
    const selectedSmsList = ref([]);
    const selectedEmailList = ref([]);
    const selectedWeChatFilterList = ref([]);

    const searchText = ref("");
    const searchedColumn = ref("");
    const searchInput = ref();
    const handleSearch = (selectedKeys, confirm, dataIndex) => {
      confirm();
      searchText.value = selectedKeys[0];
      searchedColumn.value = dataIndex;
      getTableData();
    };

    const handleReset = (clearFilters, confirm) => {
      clearFilters();
      searchText.value = "";
      confirm();
    };

    const dataList = ref([]);
    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const loading = ref(false);
    const totalCount = ref(0);
    const smsCount = ref(0);
    const emailCount = ref(0);
    const getTableData = () => {
      loading.value = false;
      request
          .get("/org", "/notice/billNoticeList", {
            page: page.value,
            limit: limit.value,
            create_start:
                dateRange.value && dateRange.value.length > 0
                    ? moment(dateRange.value[0]).format("YYYY-MM-DD")
                    : "",
            create_end:
                dateRange.value && dateRange.value.length > 0
                    ? moment(dateRange.value[1]).format("YYYY-MM-DD")
                    : "",
            sms_status:
                selectedSmsList.value && selectedSmsList.value.length > 0
                    ? selectedSmsList.value[0]
                    : null,
            email_status:
                selectedEmailList.value && selectedEmailList.value.length > 0
                    ? selectedEmailList.value[0]
                    : null,
            wechat_status:
                selectedWeChatFilterList.value &&
                selectedWeChatFilterList.value.length > 0
                    ? selectedWeChatFilterList.value[0]
                    : null,
            ownerKeyword: searchText.value,
            buildIds: selectedBuildList.value,
          })
          .then((res) => {
            dataList.value = res.list;
            total.value = res.total ? res.total : 0;
            totalCount.value = res.total && res.total;
            smsCount.value = res.smsSuccess && res.smsSuccess;
            emailCount.value = res.emailSuccess && res.emailSuccess;
          })
          .finally(() => {
            loading.value = false;
          });
    };

    const handleTableChange = (pager, filters, sorter) => {
      console.log(filters);
      page.value = pager.current;
      limit.value = pager.pageSize;
      selectedSmsList.value = filters.sms_status;
      selectedEmailList.value = filters.email_status;
      selectedBuildList.value = filters.build_name;
      selectedWeChatFilterList.value = filters.wechat_status;
    };

    const getFilterList = () => {
      request
          .get("/org", "/notice/init", {})
          .then((res) => {
            buildList.value = res.returnData.buildList;
            smsList.value = res.returnData.smsStatus;
            emailList.value = res.returnData.emailStatus;
            weChatFilterList.value = [
              {key: 1, name: "失败"},
              {key: 2, name: "成功"},
            ];
          })
          .finally(() => {
            getTableData();
          });
    };

    const columns = computed(() => {
      return [
        {
          title: "租客名称",
          dataIndex: "owner_name",
          key: "owner_name",
          ellipsis: true,
          customFilterDropdown: true,
          onFilter: (value, record) =>
              record.owner_name
                  .toString()
                  .toLowerCase()
                  .includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                console.log(searchInput.value);
                searchInput.value.focus();
              }, 100);
            }
          },
          width: 300,
        },
        {
          title: "楼宇",
          dataIndex: "build_name",
          key: "build_name",
          filters:
              buildList.value && buildList.value.length
                  ? buildList.value.map((item) => ({
                    value: item.key.toString(),
                    text: item.name,
                  }))
                  : [],
          filterMultiple: true,
          defaultFilteredValue: selectedBuildList.value,
          width: 300,
        },
        {
          title: "楼号/房号",
          dataIndex: "room_info",
          width: 200,
        },
        {
          title: "短信发送状态",
          dataIndex: "sms_status",
          key: "sms_status",
          filters:
              smsList.value && smsList.value.length
                  ? smsList.value.map((item) => ({
                    value: item.key.toString(),
                    text: item.name,
                  }))
                  : [],
          filterMultiple: false,
          defaultFilteredValue: selectedSmsList.value,
          width: 150,
        },
        {
          title: "邮箱发送状态",
          dataIndex: "email_status",
          key: "email_status",
          filters:
              emailList.value && emailList.value.length
                  ? emailList.value.map((item) => ({
                    value: item.key.toString(),
                    text: item.name,
                  }))
                  : [],
          filterMultiple: false,
          defaultFilteredValue: selectedEmailList.value,
          width: 150,
        },
        {
          title: "公众号发送状态",
          dataIndex: "wechat_status",
          key: "wechat_status",
          filters:
              weChatFilterList.value && weChatFilterList.value.length
                  ? weChatFilterList.value.map((item) => ({
                    value: item.key.toString(),
                    text: item.name,
                  }))
                  : [],
          filterMultiple: false,
          defaultFilteredValue: selectedWeChatFilterList.value,
          width: 150,
        },
        {
          title: "生成日期",
          dataIndex: "build_date",
          width: 200,
        },
        {
          title: "操作",
          dataIndex: "id",
          key: "action",
          width: 200,
        },
      ];
    });

    const init = () => {
      page.value = 1;
      getFilterList();
    };

    init();

    const onRangeChange = (dates, dateString) => {
      page.value = 1;
    };

    const state = reactive({
      selectedRowKeys: [],
      selectedRows: "",
      showModal: false,
      printList: [],

    });

    const resendNoticeVisible = ref(false);
    const resendNoticeData = ref({});
    const resendNoticeId = ref(0);
    const resendNoticeTaskKey = ref("");

    const sendAgain = (record) => {
      console.log(record.build_id);
      resendNoticeVisible.value = true;
      resendNoticeData.value = record.form_data;
      resendNoticeId.value = record.id;
      resendNoticeTaskKey.value = record.task_key;
    };

    const resendNoticeClose = () => {
      resendNoticeVisible.value = false;
    };

    const resendNoticeSuccess = () => {
      resendNoticeVisible.value = false;
      getTableData();
    };

    /* 选择行 */
    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectedRowChange,
      getCheckboxProps: record => ({
        disabled: record?.file_path?.fileUrl == undefined,
      }),
    }));
    const onSelectedRowChange = (selectedRowKeys, selectedRows) => {
      state.selectedRows = selectedRows;
      state.selectedRowKeys = selectedRowKeys;
    };

    const printReceipt = () => {
      state.printList = state.selectedRows.map((item) => {
        return item?.file_path?.fileUrl;
      });
      state.showModal = true;

    };

    // 合同预览
    const electronContractVisible = ref(false);
    const previewUrlData = ref({});
    const previewFile = (data) => {
      if (data?.file_path?.online_preview?.previewUrl) {
        previewUrlData.value = {
          previewUrl: data.file_path.online_preview.previewUrl,
          url: data.file_path.fileUrl,
        };
        electronContractVisible.value = true;
      } else {
        window.open(data?.file_path?.fileUrl);
      }
    };


    watch(
        [
          page,
          limit,
          dateRange,
          selectedBuildList,
          selectedSmsList,
          selectedEmailList,
          selectedWeChatFilterList,
        ],
        () => {
          getTableData();
        }
    );

    return {
      ...toRefs(state),
      dataList,
      pagination,
      loading,
      handleTableChange,
      columns,

      smsList,
      selectedSmsList,
      emailList,
      selectedEmailList,
      dateRange,

      handleSearch,
      handleReset,
      searchInput,

      onRangeChange,
      moment,

      totalCount,
      smsCount,
      emailCount,

      sendAgain,
      resendNoticeVisible,
      resendNoticeClose,
      resendNoticeSuccess,
      resendNoticeData,
      resendNoticeId,
      resendNoticeTaskKey,
      rowSelection,
      printReceipt,
      previewFile,
      electronContractVisible,
      previewUrlData,

    };
  },
});
</script>

<style lang="less" scoped>
.waitingNotice-list {
  padding: 10px;

  .statics {
    background: #fff;
    margin-top: 10px;
    width: 100%;
    padding: 10px;

    :deep(.ant-col) {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    :deep(.ant-statistic-title) {
      text-align: center;
    }

    :deep(.ant-statistic-content) {
      text-align: center;
    }
  }

  .btn-class {
    margin: 0 5px;
  }
}
</style>
